import { defineStore } from 'pinia';
import { userApi, type User, type ApiResponse, type LoginRequest, type RegisterRequest } from '@/api/user';

interface UserState {
  currentUser: User | null;
  users: User[];
  token: string | null;
}

// 定义更新用户信息的参数类型
interface UpdateUserData {
  username?: string;
  email?: string;
  realName?: string;
  phone?: string;
  password?: string;
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    currentUser: null,
    users: [],
    token: localStorage.getItem('token')
  }),

  getters: {
    isLoggedIn: (state) => {
      const hasToken = !!state.token
      const hasUser = !!state.currentUser
      console.log('isLoggedIn 检查:', { hasToken, hasUser })
      return hasToken && hasUser
    },
    isAdmin: (state) => {
      // 多种方式识别管理员（兼容中文角色名：管理员）
      const roles = state.currentUser?.roles || []
      const hasAdminRole = roles.some(r => {
        if (!r) return false
        const lower = r.toLowerCase()
        return lower === 'admin' || lower.includes('管理员')
      })
      const isAdminUser = 
        hasAdminRole ||
        state.currentUser?.username === 'admin' ||
        state.currentUser?.userId === 1 || // 特殊处理 user_id = 1
        (state.currentUser?.username && state.currentUser.username.toLowerCase().includes('admin')) ||
        localStorage.getItem('userRole') === 'admin' ||
        localStorage.getItem('userRole') === '管理员'
      
      console.log('isAdmin 检查:', { 
        username: state.currentUser?.username,
        userId: state.currentUser?.userId,
        roles: state.currentUser?.roles,
        storedRole: localStorage.getItem('userRole'),
        isAdminUser 
      })
      return isAdminUser
    },
    userRole: (state) => {
      // 多种方式识别管理员角色（兼容中文角色名：管理员）
      const roles = state.currentUser?.roles || []
      const hasAdminRole = roles.some(r => {
        if (!r) return false
        const lower = r.toLowerCase()
        return lower === 'admin' || lower.includes('管理员')
      })
      const isAdmin = 
        hasAdminRole ||
        state.currentUser?.username === 'admin' ||
        state.currentUser?.userId === 1 || // 特殊处理 user_id = 1
        (state.currentUser?.username && state.currentUser.username.toLowerCase().includes('admin')) ||
        localStorage.getItem('userRole') === 'admin' ||
        localStorage.getItem('userRole') === '管理员'
      
      const role = isAdmin ? 'admin' : 'user'
      
      console.log('userRole 详细检查:', { 
        username: state.currentUser?.username,
        userId: state.currentUser?.userId,
        roles: state.currentUser?.roles,
        storedRole: localStorage.getItem('userRole'),
        isAdmin,
        finalRole: role
      })
      
      return role
    },
    getUserById: (state) => (id: number) => 
      state.users.find(user => user.userId === id)
  },

  actions: {
    async login(username: string, password: string) {
      try {
        console.log('开始登录:', username);
        
        const response = await userApi.login({ username, password });
        console.log('登录响应:', response);
        
        if (response.data.operateResult === 'SUCCESS' && response.data.data) {
          this.currentUser = response.data.data;
          
          // 确保管理员用户有正确的角色信息
          if (username === 'admin' || this.currentUser.userId === 1) {
            if (!this.currentUser.roles) {
              this.currentUser.roles = ['admin'];
            } else if (!this.currentUser.roles.includes('admin')) {
              this.currentUser.roles.push('admin');
            }
          }
          
          this.token = `user-token-${Date.now()}`;
          
          // 保存到 localStorage
          localStorage.setItem('token', this.token);
          localStorage.setItem('userInfo', JSON.stringify(this.currentUser));
          localStorage.setItem('isLoggedIn', 'true');
          localStorage.setItem('userRole', this.userRole);
          
          console.log('登录成功:', { 
            user: this.currentUser, 
            isLoggedIn: this.isLoggedIn,
            userRole: this.userRole
          });
          
          return { success: true, message: '登录成功' };
        } else {
          console.log('登录失败:', response.data.errorMsg);
          return { 
            success: false, 
            message: response.data.errorMsg || '登录失败' 
          };
        }
      } catch (error: any) {
        console.error('登录错误:', error);
        return { 
          success: false, 
          message: error.response?.data?.errorMsg || '登录失败，请检查网络连接' 
        };
      }
    },

    async loginApi(username: string, password: string) {
      return this.login(username, password);
    },

    async register(userData: RegisterRequest) {
      try {
        const response = await userApi.register(userData);
        
        if (response.data.operateResult === 'SUCCESS') {
          return { success: true, message: '注册成功' };
        } else {
          return { 
            success: false, 
            message: response.data.errorMsg || '注册失败' 
          };
        }
      } catch (error: any) {
        console.error('注册错误:', error);
        return { 
          success: false, 
          message: error.response?.data?.errorMsg || '注册失败，请稍后重试' 
        };
      }
    },

    async registerApi(userData: RegisterRequest) {
      return this.register(userData);
    },

    logout() {
      this.token = null;
      this.currentUser = null;
      // 清除所有 localStorage 数据
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('isLoggedIn');
      localStorage.removeItem('userRole');
      
      console.log('用户已退出登录');
    },

    async fetchCurrentUser() {
      try {
        const userInfo = localStorage.getItem('userInfo');
        if (userInfo) {
          this.currentUser = JSON.parse(userInfo);
          console.log('从 localStorage 恢复用户:', this.currentUser);
          return this.currentUser;
        }
        return null;
      } catch (error) {
        console.error('获取当前用户信息失败:', error);
        return null;
      }
    },

    async fetchAllUsers() {
      try {
        const response = await userApi.getAllUsers();
        if (response.data.operateResult === 'SUCCESS' && response.data.data) {
          this.users = response.data.data;
          return response.data;
        } else {
          return { 
            operateResult: 'FAIL', 
            errorMsg: response.data.errorMsg || '获取用户列表失败' 
          };
        }
      } catch (error: any) {
        console.error('获取用户列表失败:', error);
        return { 
          operateResult: 'FAIL', 
          errorMsg: '获取用户列表失败，请检查网络连接' 
        };
      }
    },

    async fetchUserRoles(username: string) {
      try {
        const response = await userApi.getUserRoles(username);
        if (response.data.operateResult === 'SUCCESS') {
          return { operateResult: 'SUCCESS', roles: response.data.data as string[] };
        } else {
          return { operateResult: 'FAIL', errorMsg: response.data.errorMsg || '获取用户角色失败' };
        }
      } catch (error: any) {
        console.error('获取用户角色失败:', error);
        return { operateResult: 'FAIL', errorMsg: '获取用户角色失败，请检查网络连接' };
      }
    },

    async updateUserRoles(username: string, roleIds: number[]) {
      try {
        const response = await userApi.updateUserRoles(username, roleIds);
        if (response.data.operateResult === 'SUCCESS') {
          // 如果修改的是当前用户的角色，尝试同步到本地（仅名称，不含ID）
          if (this.currentUser && this.currentUser.username === username) {
            // 简单同步：根据常见映射更新角色名（兼容中文）
            const idToRole: Record<number, string> = { 1: 'admin', 2: 'user' };
            const idToRoleCN: Record<number, string> = { 1: '管理员', 2: '普通用户' };
            const mapped = roleIds.map(id => idToRole[id] || idToRoleCN[id]).filter(Boolean) as string[];
            this.currentUser.roles = mapped;
            localStorage.setItem('userInfo', JSON.stringify(this.currentUser));
            const isAdmin = mapped.some(r => r.toLowerCase() === 'admin' || r.includes('管理员'));
            localStorage.setItem('userRole', isAdmin ? 'admin' : 'user');
          }
          return { operateResult: 'SUCCESS' };
        } else {
          return { operateResult: 'FAIL', errorMsg: response.data.errorMsg || '更新用户角色失败' };
        }
      } catch (error: any) {
        console.error('更新用户角色失败:', error);
        return { operateResult: 'FAIL', errorMsg: '更新用户角色失败，请稍后重试' };
      }
    },

    async deleteUserById(username: string) {
      try {
        const response = await userApi.deleteUser(username);
        if (response.data.operateResult === 'SUCCESS') {
          this.users = this.users.filter(user => user.username !== username);
          return { operateResult: 'SUCCESS' };
        } else {
          return { 
            operateResult: 'FAIL', 
            errorMsg: response.data.errorMsg || '删除失败' 
          };
        }
      } catch (error: any) {
        console.error('删除用户失败:', error);
        return { 
          operateResult: 'FAIL', 
          errorMsg: '删除失败，请稍后重试' 
        };
      }
    },

    async updateUserInfo(userId: number, userData: UpdateUserData) {
      try {
        const currentUser = this.users.find(user => user.userId === userId);
        if (!currentUser) {
          return { 
            operateResult: 'FAIL', 
            errorMsg: '用户不存在' 
          };
        }

        const completeUserData: User = {
          userId: userId,
          username: userData.username || currentUser.username,
          password: userData.password || currentUser.password,
          realName: userData.realName || currentUser.realName,
          email: userData.email || currentUser.email,
          phone: userData.phone || currentUser.phone,
          createdAt: currentUser.createdAt,
          updatedAt: currentUser.updatedAt,
          roles: currentUser.roles
        };

        const response = await userApi.updateUser(completeUserData);
        if (response.data.operateResult === 'SUCCESS') {
          const index = this.users.findIndex(user => user.userId === userId);
          if (index !== -1) {
            this.users[index] = { ...this.users[index], ...userData };
          }
          
          if (this.currentUser && this.currentUser.userId === userId) {
            this.currentUser = { ...this.currentUser, ...userData };
            localStorage.setItem('userInfo', JSON.stringify(this.currentUser));
          }
          
          return { operateResult: 'SUCCESS' };
        } else {
          return { 
            operateResult: 'FAIL', 
            errorMsg: response.data.errorMsg || '更新失败' 
          };
        }
      } catch (error: any) {
        console.error('更新用户信息失败:', error);
        return { 
          operateResult: 'FAIL', 
          errorMsg: '更新失败，请稍后重试' 
        };
      }
    }
  }
});